package de.tum.in.eist.poll.controller;

import java.util.List;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.tum.in.eist.poll.client.EIST_POLL;
import de.tum.in.eist.poll.service.OnDataUpdate;
import de.tum.in.eist.poll.shared.Feedback;
import de.tum.in.eist.poll.shared.Student;

/**
 * FeedbackFetchCallback receives feedback from server
 * @author sudi
 *
 */
class FeedbackFetchCallback implements AsyncCallback<List<Feedback>> {
	OnDataUpdate<List<Feedback>> callback;
	
	FeedbackFetchCallback(OnDataUpdate<List<Feedback>> cb) {
		callback = cb;
	}
	@Override
	public void onFailure(Throwable caught) {
		// TODO Auto-generated method stub
		Window.alert("Fail! could not fetch feedback");
	}

	@Override
	public void onSuccess(List<Feedback> result) {
		if (callback != null)
			callback.onDataUpdate(result);
	}
}

/**
 * FeedbackController handles submit and fetch of feedback
 * @author sudi
 *
 */
public class FeedbackController {
	/**
	 * lecture controller to access the current lecture
	 */
	LectureController lectureController;
	
	public FeedbackController(LectureController lectureController) {
		this.lectureController = lectureController;
	}
	/**
	 * sends feedback to the server
	 * @param satisfaction The rating
	 * @param like Custom like text
	 * @param dislike Custom dislike text
	 */
	public void sendFeedback(int satisfaction, String like, String dislike) {
		EIST_POLL.getService().submitFeedback(new Feedback(lectureController.getSelected(), (Student) lectureController.userController.getUser(), satisfaction, like, dislike), new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert("bääh");
				History.back();
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				lectureController.getSelected().addStudent((Student) lectureController.userController.getUser());
				History.back();
			}
			
		});
	}
	
	/**
	 * get feedback from server
	 * @param cb is called when fetch is successfull
	 */
	public void fetchFeedback(OnDataUpdate<List<Feedback>> cb) {
		EIST_POLL.getService().requestFeedback(lectureController.getUserController().getUser(), lectureController.getSelected(), new FeedbackFetchCallback(cb));
	}
}
